<?php
declare (strict_types=1);

namespace app\controller;

use app\BaseController;

use app\model\Notice as NoticeModel;

use app\model\NoticeUserLog as NoticeUserLogModel;
use think\App;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Log;
use think\Request;
use think\Response;

class NoticeUserLog extends BaseController
{
    protected NoticeModel $model;

    protected NoticeUserLogModel $logModel;

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->model    = new NoticeModel();
        $this->logModel = new NoticeUserLogModel();
    }

    /**
     * 获取未读消息条数
     * @param Request $request
     *
     * @return Response
     */
    public function getUnreadCount(Request $request): Response
    {
        $userId = $request->param('user_id/d', 0);
        if (empty($userId)) {
            return $this->error('缺少必要参数！');
        }
        $unreadCount = $this->logModel->alias('e')
            ->join('think_notice n' , 'n.id = e.notice_id' , 'LEFT')
            ->where([
                'e.user_id' => $userId ,
                'e.is_read'   => NoticeUserLogModel::IS_READ_DEFAULT ,
            ])->count();

        return $this->success('success' , [ 'unread_count' => $unreadCount ]);
    }

    /**
     * 显示资源列表
     *
     * @param Request $request
     * @url /notice/list
     * @method GET
     * @params int page 当前页码
     * @params int pageSize 每页显示条数
     * @params int user_id 用户id
     * @params int notice_id 消息id
     *
     *
     * @return Response
     */
    public function list(Request $request)
    : Response {
        $params = $request->param();
        $where  = [
            'n.state' => NoticeModel::STATE_PUBLISHED,
        ];
        if (!empty($params['user_id'])) {
            $where['e.user_id'] = $params['user_id'];
        }
        if (!empty($params['keywords'])) {
            $where[] = ['n.title|n.keywords', 'like' , '%' . $params['keywords'] . '%'];
        }

        try {
            $query = $this->logModel->alias('e')->join('think_notice n' , 'e.notice_id = n.id' , 'LEFT')->where($where);
            $count = $query->count();
            $fields = 'e.*,n.title,n.keywords,n.content';
            $list  = $query->field($fields)->page($this->page, $this->pageSize)->order('e.is_top DESC, e.id DESC')->select();
            $data    = [
                'pageSize' => $this->pageSize ,
                'page'     => $this->page ,
                'total'    => $count ,
                'list'     => $list ,
            ];

            return $this->success('success' , $data);
        } catch (DataNotFoundException|ModelNotFoundException|DbException $e) {
            Log::error($e->getMessage());

            return $this->error('error');
        }
    }

    /**
     * 查看站内性消息详情
     *
     * @url /notice/info
     * @method GET
     *
     * @params int notice_id 消息id
     * @param Request $request
     *
     * @return Response
     */
    public function info(Request $request): Response
    {
        $id = $request->param('id/d' , 0);
        if (empty($id)) {
            return $this->error('参数错误');
        }
        $noticeLog = $this->logModel->where('id' , $id)->findOrEmpty();
        if ($noticeLog->isEmpty()) {
            return $this->error('消息不存在');
        }
        if ($noticeLog->is_read === NoticeUserLogModel::IS_READ_DEFAULT) {
            $noticeLog->is_read = NoticeUserLogModel::IS_READ_YES;
            $noticeLog->save();
        }

        $notice = $this->model->where('id' , $noticeLog->notice_id)->findOrEmpty();
        if ($notice->isEmpty()) {
            return $this->error('消息不存在');
        }
        $notice->setInc('read_num');

        $data = [
            'id'          => $noticeLog['id'] ,
            'notice_id'   => $noticeLog['notice_id'] ,
            'is_read'     => $noticeLog['is_read'] ,
            'title'       => $notice['title'] ,
            'keywords'    => $notice['keywords'] ,
            'content'     => $notice['content'] ,
            'create_time' => $notice['create_time'] ,
            'update_time' => $notice['update_time'] ,
        ];
        return $this->success('success' , $data);
    }

    /**
     * 消息置顶/取消置顶
     * @param Request $request
     *
     * @return Response
     */
    public function noticeUpEdit(Request $request): Response
    {
        $id = $request->param('id');
        if (empty($id)) {
            return $this->error('参数错误');
        }
        $notice = $this->logModel->where('id' , $id)->findOrEmpty();
        if ($notice->isEmpty()) {
            return $this->error('消息不存在');
        }
        if ($notice->is_top === NoticeUserLogModel::IS_READ_YES) {
            $notice->is_top = NoticeUserLogModel::IS_READ_DEFAULT;
        } else {
            $notice->is_top = NoticeUserLogModel::IS_READ_YES;
        }
        $notice->save();
        return $this->success();
    }
}
